import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import {
  Select,
  Button,
  Table,
  Input,
  message,
  Upload,
  Tree,
  Modal,
} from "antd";
import {
  PlusOutlined,
  ExclamationCircleFilled,
  DeleteOutlined,
  SearchOutlined,
  UploadOutlined,
} from "@ant-design/icons";
import {
  text_check,
  post_axios,
  key_find_check_value,
  box_type_list,
  random_string,
  get_suffix,
  format_time,
  status_code_list
} from "../../utils";
import "./index.scss";
import axios from "../../axios/index";

export default function AvmBoxType(props) {
  const { t } = useTranslation();
  const [tableHeight, setTableHeight] = useState(0);
  const { actions, setSpinning } = props;
  const { Option } = Select;
  const { confirm } = Modal;
  let { menu_action, user_power_lang, username, user_grade } = actions;
  user_power_lang = JSON.parse(user_power_lang);

  // 国内国外判断
  const session_company = sessionStorage.getItem("company");
  let localStorage_company = JSON.parse(localStorage.getItem("choose_company"));
  const local_company_object =
    localStorage_company &&
    localStorage_company[username] &&
    localStorage_company[username]
      ? localStorage_company[username]
      : "";

  const [company_scope, setCompany_scope] = useState("now");
  const [avm_box_list, setAvm_box_list] = useState([]);

  const getData = async () => {
    let upMsg = {
      company_id: company_scope == "now" ? local_company_object.id : "",
      company: company_scope == "now" ? local_company_object.company : "",
    };
    setSpinning(true);
    let res = await post_axios("avm_box_type", "m_query", upMsg);
    setSpinning(false);
    if (!res) return;
    setAvm_box_list(res.data_rows.rows);
  };
  const columns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: t("assets.box_type_name"),
      align: "center",
      render: (_, record) => (
        <>
          <div>
            {key_find_check_value(record.box_type, box_type_list, "msg_en")}
          </div>
        </>
      ),
    },
    {
      title: t("assets.description"),
      dataIndex: "box_type_name",
      align: "center",
    },
  ];

  // 用户数据行点击
  const [clickRowKey, setClickRowKey] = useState("");
  const [clickRow, setclickRow] = useState({});
  // 根据xy数量预先添加的空白数组
  const [blankArr, setBlankArr] = useState([]);
  // 根据已添加的货道修改空白数组之后的数组
  const [clicked_box_road_list, setClicked_box_road_list] = useState([]);
  const tableRowClick = (row) => {
    console.log(row);
    setClickRowKey(row.box_type_id);
    setclickRow(row);
    // 清空数组
    const blankRows = [];
    let { x_nu, y_nu } = row;
    for (let i = 1; i <= y_nu; i++) {
      for (let j = 1; j <= x_nu; j++) {
        blankRows.push({
          x_no: i,
          y_no: j,
          vm_box_no: "",
          vm_aisle_no: "",
          vm_aisle_label: "",
        });
      }
    }
    setBlankArr(blankRows);
    setEdit_avm_road_arr(blankRows);
    setClicked_box_road_list([]);
    get_box_road(row, blankRows);
  };

  const search_data = () => {
    initData();
  };

  const initData = () => {
    setClickRowKey("");
    setclickRow([]);
    getData();
  };

  const get_box_road = async (value, blankRows) => {
    let upMsg = {
      box_type_id: value.box_type_id,
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    setSpinning(true);
    let res = await post_axios("avm_box_type", "m_query_aisle", upMsg);
    setSpinning(false);
    if (!res) return;
    let rows = res.data_rows.rows;
    if (rows.length !== 0) {
      let newRows = JSON.parse(JSON.stringify(blankRows));
      let { x_nu, y_nu } = value;
      rows.forEach((item) => {
        let idx = (item.x_no - 1) * x_nu + item.y_no - 1;
        newRows[idx] = item;
      });
      setClicked_box_road_list(newRows);
    }
  };

  // 添加/修改
  const [editDialogshow, setEditDialogshow] = useState(false);
  const [editDialogtitle, setEditDialogtitle] = useState("");

  const [edit_box_type_name, setEdit_box_type_name] = useState("");
  const [edit_box_type, setEdit_box_type] = useState("");
  const [edit_x_nu, setEdit_x_nu] = useState("");
  const [edit_y_nu, setEdit_y_nu] = useState("");

  const typeAddShow = async () => {
    setEditDialogshow(true);
    setEditDialogtitle(t("common.add"));
    setEdit_box_type_name("");
    setEdit_box_type("");
    setEdit_x_nu("");
    setEdit_y_nu("");
  };

  const editConfirm = async () => {
    let upMsg = {
      x_nu: edit_x_nu,
      y_nu: edit_y_nu,
      box_type: edit_box_type,
      box_type_name: edit_box_type_name,
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    setSpinning(true);
    let res = await post_axios("avm_box_type", "m_add", upMsg);
    setSpinning(false);
    if (!res) return;
    message.success({
      content: editDialogtitle + " " + t("common.successfully"),
    });
    setEditDialogshow(false);
    search_data();
  };

  const [avm_road_show, setAvm_road_show] = useState(false);
  const [edit_avm_road_arr, setEdit_avm_road_arr] = useState([]);
  const set_avm_road_func = () => {
    setAvm_road_show(true);
  };
  const avm_road_change = (value, index, type) => {
    let newObj = edit_avm_road_arr;
    newObj[index][type] = value;
    setEdit_avm_road_arr(newObj);
  };
  const edit_road_confirm = async () => {
    let ipt_arr = JSON.parse(JSON.stringify(edit_avm_road_arr));
    let ipt_success_arr = ipt_arr.filter((item) => {
      return (
        item.vm_box_no !== "" &&
        item.vm_aisle_no !== "" &&
        item.vm_aisle_label !== ""
      );
    });

    let upMsg = {
      box_type_id: clickRowKey,
      vm: ipt_success_arr,
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    console.log(upMsg);
    setSpinning(true);
    let res = await post_axios("avm_box_type", "m_add_aisle", upMsg);
    setSpinning(false);
    if (!res) return;
    message.success({
      content: t("common.change_success"),
    });
    search_data();
    setAvm_road_show(false);
  };

  // 删除货柜
  const delete_box = async () => {
    if (clickRowKey === "") {
      message.warning({
        content: t("assets.select_a_box"),
      });
      return;
    }
    confirm({
      title: t("common.info"),
      icon: <ExclamationCircleFilled />,
      content: (
        <div>
          {t("assets.sure_to_delete_box")}
          <strong>{clickRow.box_type_name}</strong>
        </div>
      ),
      onOk: async () => {
        let upMsg = {
          box_type_id: clickRowKey,
          x_nu: clickRow.x_nu,
          y_nu: clickRow.y_nu,
          box_type: clickRow.box_type,
          box_type_name: clickRow.box_type_name,
          company_id: local_company_object.id,
          company: local_company_object.company,
        };
        let res = await post_axios("avm_box_type", "m_del", upMsg);
        if (!res) return;
        message.success({
          content: t("common.delete_success"),
        });
        search_data();
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };

  const [oss_params, setOss_params] = useState({});
  const get_oss_params = async () => {
    let upMsg = {
      op_type: "IMPORT",
    };
    let res = await post_axios("generate_post_policy", "m_query", upMsg);
    if (!res) return;
    setOss_params(res.data);
  };

  // 导入
  const [import_data_show, setImport_data_show] = useState(false);
  const [choose_file_show, setChoose_file_show] = useState(false);
  const [import_ranks_list, setImport_ranks_list] = useState([]);
  const import_avm = async () => {
    await get_import_ranks_data();
    setImport_data_show(true);
  };
  const download_template_func = async () => {
    let upMsg = {
      import_type: "Machine Cabinet Type",
    };
    let res = await post_axios("task_import", "m_query_template", upMsg);
    if (!res) return;
    window.open(`https://testweb.easytouch.top/${res.data.template_name}`);
  };
  const [fileList, setFileList] = useState([]);
  const upload_change = (data) => {
    console.log(data);
    const { file, fileList } = data;
    if (fileList.length === 0) return;
    const uploadFile = fileList[0];
    const isJPG =
      uploadFile.originFileObj.type === "application/vnd.ms-excel" ||
      uploadFile.originFileObj.type ===
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    const isLt10M = uploadFile.originFileObj.size / 1024 / 1024 <= 10;
    if (!isJPG) {
      message.warning({
        content: t("assets.only_excel"),
      });
      return false;
    } else if (!isLt10M) {
      message.warning({
        content: t("assets.only_500k"),
      });

      return false;
    } else {
      setFileList([uploadFile.originFileObj]);
      console.log(fileList);
    }
  };
  const picUpload = (file) => {
    let fileObj = file;
    let data = oss_params;
    let ossData = new FormData();
    ossData.append("name", fileObj.name);
    //key就代表文件层级和阿里云上的文件名
    let filename = fileObj.name;
    let picName = random_string(32) + get_suffix(filename);
    let keyValue = data.dir + picName;
    ossData.append("key", keyValue);
    ossData.append("policy", data.policy);
    ossData.append("OSSAccessKeyId", data.access_id);
    ossData.append("success_action_status", "200");
    ossData.append("signature", data.signature);
    ossData.append("file", fileObj.raw);

    return new Promise((resolve, reject) => {
      axios
        .post(`https://${data.host}`, ossData, {
          header: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          if (res.status == 200) {
            resolve(picName);
          } else {
            reject(false);
          }
        })
        .catch((error) => {
          reject(false);
        });
    });
  };
  const upload_import_file_confirm = async () => {
    if (Object.keys(fileList).length == 0) {
      message.warning({
        content: t("goods.choose_pic"),
      });
      return;
    }
    let upload_res = await picUpload(fileList[0]);
    let upMsg = {
      import_type: "Machine Cabinet Type",
      import_file_name: upload_res,
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    setSpinning(true);
    let res = await post_axios("avm_box_type", "m_import", upMsg);
    setSpinning(false);
    if (!res) return;
    setChoose_file_show(false);
    get_import_ranks_data();
  };
  const get_import_ranks_data = async () => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      import_type: "Machine Cabinet Type",
    };
    setSpinning(true);
    let res = await post_axios("task_import", "m_query", upMsg);
    setSpinning(false);
    if (!res) return;
    setImport_ranks_list(res.data_rows.rows);
  };

  const add_import_ranks = async () => {
    await get_oss_params();
    setFileList([]);
    setChoose_file_show(true);
  };
  const download_import_data = (item) => {
    window.open(item.result_url);
  };
  const delete_import_data = async (item) => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      id: item.id,
      import_file_name: item.import_file_name,
    };
    setSpinning(true);
    let res = await post_axios("task_import", "m_del", upMsg);
    setSpinning(false);
    if (!res) return;
    message.success({
      content: t("common.delete_success"),
    });
    get_import_ranks_data();
  };

  const importRanksColumns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: t("operate.time"),
      align: "center",
      render: (_, record) => (
        <>{record.op_time ? format_time(record.op_time, "type_s") : ""}</>
      ),
    },
    {
      title: t("transaction_flow.file_name"),
      align: "center",
      width: 300,
      dataIndex: "import_file_name",
    },
    {
      title: t("transaction_flow.status"),
      align: "center",
      render: (_, record) => (
        <>{text_check(status_code_list[record.status_code])}</>
      ),
    },
    {
      title: t("transaction_flow.operation"),
      align: "center",
      render: (_, record) => (
        <>
          <Button
            size="small"
            type="primary"
            style={{
              marginRight: "10px",
            }}
            onClick={() => download_import_data(record)}
            disabled={record.status_code !== "Success"}
          >
            {t("transaction_flow.download")}
          </Button>
          <Button
            size="small"
            type="primary"
            danger
            onClick={() => delete_import_data(record)}
          >
            {t("transaction_flow.delete")}
          </Button>
        </>
      ),
    },
  ];

  useEffect(() => {
    // 挂载后或者更新后的操作
    getData().then(() => {
      const tabBoxHeight =
        document.getElementsByClassName("avm_box_type")[0].scrollHeight;
      const tableHeight =
        user_grade < 10 ? tabBoxHeight - 56 - 70 : tabBoxHeight - 56 - 30;
      setTableHeight(tableHeight);
    });
  }, []);
  return (
    <>
      <div className="avm_box_type modules">
        {user_grade < 10 ? (
          <div className="screen_ipt">
            <div className="ipt_box">
              <div className="ipt_box_title">{t("system_manager.company")}</div>
              <Select
                size="small"
                placeholder=" "
                options={[
                  {
                    label: t("system_manager.current_selected"),
                    value: "now",
                    key: "now",
                  },
                  {
                    label: t("system_manager.all"),
                    value: "*",
                    key: "*",
                  },
                ]}
                value={company_scope}
                onChange={(value) => setCompany_scope(value)}
              />
            </div>
          </div>
        ) : (
          ""
        )}
        <div className="screen_btn">
          <div className="btn_box">
            {/* 添加 */}
            {menu_action.indexOf("m_add") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<PlusOutlined style={{ color: "#1677FF" }} />}
                onClick={typeAddShow}
              >
                {text_check(user_power_lang["m_add"])}
              </Button>
            ) : (
              ""
            )}
            {/* 导入 */}
            {menu_action.indexOf("m_import") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<PlusOutlined style={{ color: "#1677FF" }} />}
                onClick={import_avm}
              >
                {text_check(user_power_lang["m_import"])}
              </Button>
            ) : (
              ""
            )}
            {/* 删除 */}
            {menu_action.indexOf("m_del") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<DeleteOutlined style={{ color: "#1677FF" }} />}
                onClick={delete_box}
              >
                {text_check(user_power_lang["m_del"])}
              </Button>
            ) : (
              ""
            )}
            {/* 查询 */}
            {menu_action.indexOf("m_query") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<SearchOutlined style={{ color: "#1677FF" }} />}
                onClick={search_data}
              >
                {text_check(user_power_lang["m_query"])}
              </Button>
            ) : (
              ""
            )}
          </div>
        </div>
        <div className="table_box">
          <div
            className="noPage-table"
            style={{
              width: "29.8vw",
            }}
          >
            <Table
              dataSource={avm_box_list}
              size="small"
              bordered
              columns={columns}
              rowKey="box_type_id"
              virtual
              scroll={{
                y: tableHeight,
              }}
              onRow={(record) => {
                return {
                  onClick: () => tableRowClick(record), // 点击行
                };
              }}
              rowClassName={(record, index) => {
                if (record.box_type_id == clickRowKey) {
                  return "row_clicked_style";
                }
              }}
              rowHoverable={false}
              pagination={false}
            />
          </div>
          {clickRowKey !== "" ? (
            <div
              className="avm_road_content"
              style={{
                width: "70vw",
                background: "white",
              }}
            >
              {clicked_box_road_list.length == 0 ? (
                <div
                  className="manager_msg"
                  onClick={set_avm_road_func}
                  style={{ cursor: "pointer" }}
                >
                  {t("assets.click_to_set_box")}
                </div>
              ) : (
                <div className="avm_road_line">
                  <div
                    className="edit_road_content"
                    style={{
                      width: clickRow.x_nu * 100 + 10 + "px",
                      height: clickRow.y_nu * 90 + "px",
                    }}
                  >
                    {clicked_box_road_list.map((item) => {
                      return (
                        <div
                          className={[
                            item.vm_box_no !== "" &&
                            item.vm_aisle_no !== "" &&
                            item.vm_aisle_label !== ""
                              ? "ipt_success_style edit_road_box"
                              : "edit_road_box",
                          ]}
                          key={item.x_no + "_" + item.y_no}
                          style={{ width: "90px", height: "80px" }}
                        >
                          <div className="ipt_box_xytitle">
                            x:{item.x_no},y:{item.y_no}
                          </div>
                          <div className="edit_road_ipt small_size">
                            <div className="edit_road_ipt_title">
                              {t("assets.vm_box_no")}
                            </div>
                            <Input
                              defaultValue={item.vm_box_no}
                              size="small"
                              disabled
                            />
                          </div>
                          <div className="edit_road_ipt small_size">
                            <div className="edit_road_ipt_title">
                              {t("assets.vm_aisle_no")}
                            </div>
                            <Input
                              defaultValue={item.vm_aisle_no}
                              size="small"
                              disabled
                            />
                          </div>
                          <div className="edit_road_ipt small_size">
                            <div className="edit_road_ipt_title">
                              {t("assets.vm_aisle_label")}
                            </div>
                            <Input
                              defaultValue={item.vm_aisle_label}
                              size="small"
                              disabled
                            />
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}
            </div>
          ) : (
            ""
          )}
        </div>
      </div>
      {/* 添加 */}
      <Modal
        title={editDialogtitle}
        open={editDialogshow}
        onOk={editConfirm}
        onCancel={() => setEditDialogshow(false)}
        classNames={{ body: "edit_dialog_body" }}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">{t("assets.box_type_name")}</div>
          <Select
            placeholder=" "
            allowClear={false}
            value={edit_box_type}
            onChange={(value) => setEdit_box_type(value)}
          >
            {Object.keys(box_type_list).map((key) => {
              return (
                <Option
                  value={box_type_list[key].value}
                  key={box_type_list[key].value}
                >
                  {text_check(box_type_list[key])}
                </Option>
              );
            })}
          </Select>
        </div>
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">{t("assets.box_name")}</div>
          <Input
            placeholder=" "
            value={edit_box_type_name}
            onChange={(e) => setEdit_box_type_name(e.target.value)}
          />
        </div>
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">{t("assets.box_column")}</div>
          <Input
            placeholder=" "
            value={edit_x_nu}
            onChange={(e) => setEdit_x_nu(e.target.value)}
          />
        </div>
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">{t("assets.box_row")}</div>
          <Input
            placeholder=" "
            value={edit_y_nu}
            onChange={(e) => setEdit_y_nu(e.target.value)}
          />
        </div>
      </Modal>

      <Modal
        title={t("assets.set_road")}
        open={avm_road_show}
        onOk={edit_road_confirm}
        onCancel={() => setAvm_road_show(false)}
        classNames={{
          body: "edit_dialog_body avm_box_type_dialog",
          wrapper: "fullscreen",
        }}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div
          className="edit_road_content"
          style={{
            width: clickRow.x_nu * 130 + 10 + "px",
            height: tableHeight + 100,
            overflow: "auto",
          }}
        >
          {edit_avm_road_arr.map((item, index) => {
            return (
              <div
                key={item.x_no + "_" + item.y_no}
                // className={[
                //   item.vm_box_no !== "" &&
                //   item.vm_aisle_no !== "" &&
                //   item.vm_aisle_label !== ""
                //     ? "ipt_success_style edit_road_box"
                //     : "edit_road_box",
                // ]}
                className="edit_road_box"
              >
                <div className="ipt_box_xytitle">
                  x:{item.x_no},y:{item.y_no}
                </div>
                <div className="edit_road_ipt">
                  <div className="edit_road_ipt_title">
                    {t("assets.vm_box_no")}
                  </div>
                  <Input
                    size="small"
                    onChange={(e) => {
                      return avm_road_change(
                        e.target.value,
                        index,
                        "vm_box_no"
                      );
                    }}
                  />
                </div>
                <div className="edit_road_ipt">
                  <div className="edit_road_ipt_title">
                    {t("assets.vm_aisle_no")}
                  </div>
                  <Input
                    size="small"
                    onChange={(e) => {
                      return avm_road_change(
                        e.target.value,
                        index,
                        "vm_aisle_no"
                      );
                    }}
                  />
                </div>
                <div className="edit_road_ipt">
                  <div className="edit_road_ipt_title">
                    {t("assets.vm_aisle_label")}
                  </div>
                  <Input
                    size="small"
                    onChange={(e) => {
                      return avm_road_change(
                        e.target.value,
                        index,
                        "vm_aisle_label"
                      );
                    }}
                  />
                </div>
              </div>
            );
          })}
        </div>
      </Modal>

      {/* 导入 */}
      <Modal
        title={t("assets.import")}
        open={import_data_show}
        onOk={false}
        onCancel={() => setImport_data_show(false)}
        classNames={{ body: "edit_dialog_body", wrapper: "edit_900_style" }}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div className="export_btn">
          <div className="btn_box">
            {/* 添加 */}
            <Button
              size="small"
              type="text"
              icon={<PlusOutlined style={{ color: "#1677FF" }} />}
              onClick={add_import_ranks}
            >
              {text_check(user_power_lang["m_add"])}
            </Button>
            {/* 查询 */}
            <Button
              size="small"
              type="text"
              icon={<SearchOutlined style={{ color: "#1677FF" }} />}
              onClick={get_import_ranks_data}
            >
              {text_check(user_power_lang["m_query"])}
            </Button>
          </div>
        </div>

        <div className="noPage-table" style={{ height: "300px" }}>
          <Table
            dataSource={import_ranks_list}
            size="small"
            bordered
            columns={importRanksColumns}
            rowKey="import_file_name"
            virtual
            scroll={{
              y: 300,
            }}
            rowHoverable={false}
            pagination={false}
          />
        </div>
      </Modal>

      <Modal
        title={t("assets.import")}
        open={choose_file_show}
        onOk={upload_import_file_confirm}
        onCancel={() => setChoose_file_show(false)}
        classNames={{ body: "edit_dialog_body" }}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">{t("assets.download_template")}</div>
          <Button type="primary" onClick={download_template_func}>
            {t("assets.download_template")}
          </Button>
        </div>

        <div className="dialog_ipt_box">
          <div className="ipt_box_title">{t("assets.choose_file")}</div>
          <Upload
            onChange={upload_change}
            onRemove={(file) => {
              const index = fileList.indexOf(file);
              const newFileList = fileList.slice();
              newFileList.splice(index, 1);
              setFileList(newFileList);
            }}
            beforeUpload={() => false}
            maxCount={1}
            fileList={fileList}
          >
            <Button icon={<UploadOutlined />}>Select File</Button>
          </Upload>
        </div>
      </Modal>
    </>
  );
}
